import React from 'react';
import { UploadOutlined } from '@ant-design/icons';
import { Button, Upload, Modal, message, Form } from 'antd';
import ProForm, { ProFormDatePicker, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { useModel } from 'umi';
import { nation } from './nation';
import styles from './BaseView.less';
import { currentUserUsingGET, updateUsingPOST2 } from '@/services/api/User';
import moment from 'moment';
import { useState } from 'react';

const BaseView: React.FC = () => {
  const { initialState, loading, setInitialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [ uploadUrl, setUploadUrl ] = useState<string>();

  // 上传头像
  const onUpload = async (file: any) => {
    if (file?.file?.status === 'done') {
      await updateUsingPOST2({ photo: file.file.response.data.fileUrl, id: currentUser?.id }).then(
        message.success('上传成功'),
      );
      // 更新初始状态里的currentUser
      const userInfo = await currentUserUsingGET();
      setInitialState((s) => ({ ...s, currentUser: userInfo.data }));
    }
  };

  // 上传简历附件
  const onUploadAttachment = async (file: any) => {
    console.log(file);
    if (file?.file?.status === 'done') {
      const fileUrl = file.file.response.data.fileUrl;
      console.log(fileUrl);
      setUploadUrl(fileUrl);
      message.success('上传成功');
      return fileUrl;
    }
  };

  // 移除简历附件
  const onRemoveAttachment = async () => {
      setUploadUrl('');
      message.success('移除成功')
  };

  const getUrlLast = (url: string) => {
    const index = url.lastIndexOf('/');
    return url.substring(index + 1, url.length);
  };


  // 头像组件 方便以后独立，增加裁剪之类的功能
  const AvatarView = ({ avatar }: { avatar: string }) => (
    <>
      <div className={styles.avatar_title}>头像</div>
      <div className={styles.avatar}>
        <img src={avatar} alt="avatar" />
      </div>
      <Upload
        showUploadList={false}
        action="http://localhost:8000/api/upload/uploadFile"
        onChange={onUpload}
      >
        <div className={styles.button_view}>
          <Button>
            <UploadOutlined />
            上传头像
          </Button>
        </div>
      </Upload>
    </>
    // console.log(file);
  );

  const getAvatarURL = () => {
    if (currentUser) {
      if (currentUser.photo) {
        return currentUser.photo;
      }
      const url = 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
      return url;
    }
    return '';
  };

  const waitTime = (time: number = 100) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(true);
      }, time);
    });
  };

  const handleFinish = async (values: Record<string, any>) => {
    await waitTime(1000);
    await updateUsingPOST2({
      ...values,
      id: currentUser?.id,
      valid: true,
      attachment: uploadUrl,
    }).then(() => {
      Modal.success({
        content: '更新基本信息成功',
      });
    });
    // 更新初始状态里的currentUser
    const userInfo = await currentUserUsingGET();
    setInitialState((s) => ({ ...s, currentUser: userInfo.data }));
  };

  return (
    <div className={styles.baseView}>
      {loading ? null : (
        <>
          <div className={styles.left}>
            <ProForm
              layout="vertical"
              onFinish={handleFinish}
              submitter={{
                resetButtonProps: {
                  style: {
                    display: 'none',
                  },
                },
                submitButtonProps: {
                  children: '更新基本信息',
                },
              }}
              initialValues={{
                ...currentUser,
              }}
              // hideRequiredMark
            >
              <ProFormText
                width="md"
                name="name"
                label="姓名"
                rules={[
                  {
                    required: true,
                    message: '请输入您的姓名!',
                  },
                ]}
              />
              <ProFormText
                width="md"
                name="email"
                label="邮箱"
                rules={[
                  {
                    required: true,
                    message: '请输入您的邮箱!',
                  },
                ]}
              />
              <ProFormText
                width="md"
                name="phone"
                label="联系电话"
                rules={[
                  {
                    required: true,
                    message: '请输入您的联系电话!',
                  },
                ]}
              />
              <ProFormText
                width="md"
                name="identityNum"
                label="身份证号码"
                rules={[
                  {
                    required: true,
                    message: '请输入您的身份证号码!',
                  },
                ]}
              />
              <ProFormSelect
                width="md"
                name="politicsStatus"
                label="政治面貌"
                options={[
                  {
                    value: '群众',
                    label: '群众',
                  },
                  {
                    value: '团员',
                    label: '团员',
                  },
                  {
                    value: '预备党员/中共党员',
                    label: '预备党员/中共党员',
                  },
                ]}
              />
              <ProFormSelect
                width="md"
                name="maritalStatus"
                label="婚姻状况"
                options={[
                  {
                    value: '未婚',
                    label: '未婚',
                  },
                  {
                    value: '已婚',
                    label: '已婚',
                  },
                ]}
              />
              <ProFormText
                width="md"
                name="school"
                label="毕业院校"
                rules={[
                  {
                    required: true,
                    message: '请输入您的毕业院校!',
                  },
                ]}
              />
              <ProFormDatePicker
                width="md"
                name="graduationDate"
                label="毕业时间"
                rules={[
                  {
                    required: true,
                    message: '请输入您的毕业时间!',
                  },
                ]}
                transform={(value) => {
                  return {
                    graduationDate: moment(value).format('YYYY-MM-DDT00:00:00'),
                  };
                }}
              />
              <ProFormText
                width="md"
                name="major"
                label="所学专业"
                rules={[
                  {
                    required: true,
                    message: '请输入您的所学专业!',
                  },
                ]}
              />
              <ProFormSelect
                options={[
                  {
                    value: '博士研究生/博士后',
                    label: '博士研究生/博士后',
                  },
                  {
                    value: '硕士研究生',
                    label: '硕士研究生',
                  },
                  {
                    value: '大学本科',
                    label: '大学本科',
                  },
                  {
                    value: '大学专科',
                    label: '大学专科',
                  },
                  {
                    value: '职业高中',
                    label: '职业高中',
                  },
                  {
                    value: '技校',
                    label: '技校',
                  },
                  {
                    value: '高中',
                    label: '高中',
                  },
                  {
                    value: '中专',
                    label: '中专',
                  },
                  {
                    value: '初中及以下',
                    label: '初中及以下',
                  },
                ]}
                width="md"
                name="education"
                label="最高学历"
                rules={[
                  {
                    required: true,
                    message: '请输入您的最高学历!',
                  },
                ]}
              />
              <ProFormSelect
                options={[
                  {
                    value: '名誉博士',
                    label: '名誉博士',
                  },
                  {
                    value: '博士',
                    label: '博士',
                  },
                  {
                    value: '硕士',
                    label: '硕士',
                  },
                  {
                    value: '学士',
                    label: '学士',
                  },
                  {
                    value: '双学位博士',
                    label: '双学位博士',
                  },
                  {
                    value: '双学位硕士',
                    label: '双学位硕士',
                  },
                  {
                    value: '双学位学士',
                    label: '双学位学士',
                  },
                  {
                    value: '无',
                    label: '无',
                  },
                ]}
                width="sm"
                name="degree"
                label="最高学位"
                rules={[
                  {
                    required: true,
                    message: '请输入您的最高学位!',
                  },
                ]}
              />

              <ProFormSelect
                width="sm"
                name="nation"
                label="民族"
                rules={[
                  {
                    required: true,
                    message: '请选择您的民族!',
                  },
                ]}
                options={nation}
              />
              <Form.Item
                name="attachment"
                label="简历附件"
                tooltip={'仅限上传一个文件'}
              >
                <Upload
                  name="file"
                  action="http://localhost:8000/api/upload/uploadFile"
                  onChange={onUploadAttachment}
                  onRemove={onRemoveAttachment}
                  maxCount={1}
                  defaultFileList={
                    currentUser?.attachment
                      ? [
                          {
                            uid: '-1',
                            name: getUrlLast(currentUser?.attachment),
                            status: 'done',
                            url: currentUser?.attachment,
                          },
                        ]
                      : undefined
                  }
                >
                  <Button icon={<UploadOutlined />}>点击上传附件</Button>
                </Upload>
              </Form.Item>
            </ProForm>
          </div>
          <div className={styles.right}>
            <AvatarView avatar={getAvatarURL()} />
          </div>
        </>
      )}
    </div>
  );
};

export default BaseView;
